/*
 * @Author: 晟松
 * @Date: 2021-11-29 23:33:14
 * @LastEditors: 晟松
 * @LastEditTime: 2022-03-06 19:25:18
 * @FilePath: \mini-vue3d:\Code\node\koa2\volunteer-service\src\main\db\index.js
 * @Description: orm根据model创建数据库表和关联
 */
const { Sequelize } = require("sequelize");
import config from "../config";
import requireDirectory from "require-directory";
import { oneToOneReletion, oneToManyReletion } from "./relationCreate";
// 方法 3: 分别传递参数 (其它数据库)
// const sequelize = new Sequelize("cheng", "root", "123456", {
//   host: "localhost",
//   dialect: "mysql" /* 选择 'mysql' | 'mariadb' | 'postgres' | 'mssql' 其一 */,
//   freezeTableName: true,
// });

const sequelize = new Sequelize(config.db);

// 存储sequelize.define返回的模型
let modelMap = {};

// 加载模型
requireDirectory(module, "../model", {
    visit: (obj) => {
        // if (obj.modelName == "user" || obj.modelName == "test") return;
        if (obj.modelName) {
            modelMap[obj.modelName] = sequelize.define(
                obj.modelName,
                obj.attributes,
                obj.options
            );
        }
    },
});

// 在这里建立关联关系，这里就需要手动定义了
// console.log('modelMap: ', modelMap);
// 创建一对一关系，外键在modelMap['test']里面定义
// 赋值的 modelMap['user'].test 是为了让关联创建的时候方便一些
modelMap["user"].test = modelMap["user"].hasOne(modelMap["test"]);
modelMap["test"].user = modelMap["test"].belongsTo(modelMap["user"]);

let relationArr = ["student", "school", "resident", "community"];
// 建立一对一关系
oneToOneReletion(modelMap, relationArr, "login");
// 建立一对多关系
oneToManyReletion(modelMap, "school", "student");
oneToManyReletion(modelMap, "community", "resident");
oneToManyReletion(modelMap, "school", "school"); //主要处理校级管理员和院级辅导员的关系

// 建立多对多关系,主要是大型志愿服务和学生的关系
modelMap["groupVol"].belongsToMany(modelMap["student"], {
    through: modelMap["student_groupVol"],
});
modelMap["student"].belongsToMany(modelMap["groupVol"], {
    through: modelMap["student_groupVol"],
});

// 同步所有模型
// sequelize.sync({ alter: true });
sequelize.sync()

module.exports = sequelize;
